package com.marketsim.analysis;

import com.marketsim.utils.BigDecimalUtils;

import java.math.BigDecimal;
import java.math.RoundingMode;
import java.util.ArrayList;
import java.util.List;

/**
 * Created by Alex on 05.04.2014.
 */
public class PortfolioUtils {

    public static <T> List<BigDecimal> getReturns(List<T> data, BigDecimalConverter converter) {
        List<BigDecimal> inputList = new ArrayList<>(data.size());
        data.stream().map(converter::convert).sorted().forEach((val) -> inputList.add(val));

        List<BigDecimal> result = new ArrayList<>(inputList.size() - 1);
        for (int i = 1; i < inputList.size(); i++) {
            result.add(inputList.get(i).divide(inputList.get(i - 1), BigDecimalUtils.SCALE, RoundingMode.HALF_UP).subtract(BigDecimal.ONE));
        }
        return result;
    }

    public static List<BigDecimal> getReturnOfPortfolio(List<List<BigDecimal>> historicalReturns, List<Double> allocation) {
        if (historicalReturns.size() != allocation.size()) {
            throw new IllegalArgumentException();
        }
        List<BigDecimal> result = new ArrayList<BigDecimal>(historicalReturns.get(0).size());
        for (int i = 0; i < historicalReturns.get(0).size(); i++) {
            BigDecimal currentReturn = BigDecimal.ZERO;
            for (int k=0; k<historicalReturns.size();k++) {
                List<BigDecimal> stockReturns = historicalReturns.get(k);
                currentReturn = currentReturn.add(stockReturns.get(i).multiply(new BigDecimal(allocation.get(k))));
            }
            result.add(currentReturn);
        }
        return result;
    }
}
